package net.pws.common.poi;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class CellOverriderFactory {

	private static final int MAX_WIDTH = 200;

	private static final int MAX_HEIGT = 200;

	public static CellOverrider createText(String text) {
		TextOverrider overrider = new TextOverrider();
		overrider.setText(text);
		return overrider;
	}

	public static CellOverrider createImage(String path, int format, int width,
			int height) {
		ImageOverrider overrider = new ImageOverrider();
		overrider.setPath(path);
		overrider.setFormat(format);
		overrider.setWidth(width);
		overrider.setHeight(height);
		return overrider;
	}

	public static CellOverrider createJpg(String path, int maxWidth,
			int maxHeight) {
		Size size = computeSize(path, maxWidth, maxHeight);
		return createImage(path, XWPFDocument.PICTURE_TYPE_JPEG,
				size.getWidth(), size.getHeight());
	}

	public static CellOverrider createJpg(String path) {
		return createJpg(path, MAX_WIDTH, MAX_HEIGT);
	}

	private static Size computeSize(String path, int maxWidth, int maxHeight) {
		Size size = new Size();
		try {
			BufferedImage bi = ImageIO.read(new File(path));
			int srcWidth = bi.getWidth();
			int srcHeight = bi.getHeight();

			float scaleWidth = (float) maxWidth / (float) srcWidth;
			float scaleHeight = (float) maxHeight / (float) srcHeight;
			float scale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight;
			size.setWidth((int) (scale * srcWidth));
			size.setHeight((int) (scale * srcHeight));
		} catch (IOException e) {
		}

		return size;
	}

	private static class Size {
		int width = 0;
		int height = 0;

		public int getWidth() {
			return width;
		}

		public void setWidth(int width) {
			this.width = width;
		}

		public int getHeight() {
			return height;
		}

		public void setHeight(int height) {
			this.height = height;
		}
	}
}
